import CryptoJS from 'crypto-js';

const TOKEN_KEY = 'mall_token';
const USER_KEY = 'mall_user';

// 后台管理系统独立的存储键
const ADMIN_TOKEN_KEY = 'mall_admin_token';
const ADMIN_USER_KEY = 'mall_admin_user';

// 密码加密
export const encryptPassword = (password) => {
  return CryptoJS.SHA256(password).toString();
};

// 保存token
export const setUserToken = (token) => {
  localStorage.setItem(TOKEN_KEY, token);
};

// 获取token
export const getUserToken = () => {
  return localStorage.getItem(TOKEN_KEY);
};

// 移除token
export const removeUserToken = () => {
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(USER_KEY);
};

// 保存用户信息
export const setUserInfo = (userInfo) => {
  localStorage.setItem(USER_KEY, JSON.stringify(userInfo));
};

// 获取用户信息
export const getUserInfo = () => {
  const userInfo = localStorage.getItem(USER_KEY);
  console.log('获取用户信息:', userInfo);
  return userInfo ? JSON.parse(userInfo) : null;
};

// 检查是否已登录
export const isUserAuthenticated = () => {
  return !!getUserToken();
};

// 生成随机token
export const generateToken = () => {
  return CryptoJS.lib.WordArray.random(128/8).toString();
};

// 前台用户专用函数（保持兼容性）
// export const setUserToken = setToken;

// 后台管理员专用函数
export const setAdminToken = (token) => {
  localStorage.setItem(ADMIN_TOKEN_KEY, token);
};

export const getAdminToken = () => {
  return localStorage.getItem(ADMIN_TOKEN_KEY);
};

export const removeAdminToken = () => {
  localStorage.removeItem(ADMIN_TOKEN_KEY);
  localStorage.removeItem(ADMIN_USER_KEY);
};

export const setAdminUserInfo = (userInfo) => {
  localStorage.setItem(ADMIN_USER_KEY, JSON.stringify(userInfo));
};

export const getAdminUserInfo = () => {
  const userInfo = localStorage.getItem(ADMIN_USER_KEY);
  console.log('获取管理员用户信息:', userInfo);
  console.log('管理员用户信息:', JSON.parse(userInfo));
  return userInfo ? JSON.parse(userInfo) : null;
};

export const isAdminAuthenticated = () => {
  return !!getAdminToken();
}; 